#include "head.h"

// 判断命令是否需要路径
int needs_path(int operation) 
{
    return operation != pwd && operation != ls; // `pwd` 和 `ls` 不需要路径
}

int cmd_split(char *buf, train_t *command_data) 
{
    char *command_str;
    command_str = strtok(buf, " \n"); // 使用 \n 以处理 fgets 引入的换行符

    // 确定命令操作
    if (strcmp(command_str, "ls") == 0)
        command_data->op = ls;
    else if (strcmp(command_str, "cd") == 0)
        command_data->op = cd;
    else if (strcmp(command_str, "pwd") == 0)
        command_data->op = pwd;
    else if (strcmp(command_str, "download") == 0)
        command_data->op = download;
    else if (strcmp(command_str, "upload") == 0)
        command_data->op = upload;
    else if (strcmp(command_str, "rm") == 0)
        command_data->op = rm;
    else if (strcmp(command_str, "cdir") == 0)
        command_data->op = cdir;
    else
    {
        return -1; // 未知命令
    }

    // 获取命令的下一部分（路径）
    command_str = strtok(NULL, " \n");

    // 如果命令需要路径且提供了路径
    if (needs_path(command_data->op)) 
    {
        if (command_str != NULL) 
        {
            strcpy(command_data->path, command_str);
            // 检查是否有额外的参数
            if ((command_str = strtok(NULL, " \n")) != NULL) 
            {
                return -1; // 参数过多
            }
        } 
        else 
        {
            // 需要路径但未提供路径
            return -1;
        }
    } 
    else
    {
        if (command_str != NULL) 
        {
            // 对于不需要路径的命令，如 `ls` 和 `pwd`，如果有额外参数，也返回错误
            return -1;
        }
    }
    return 0;
}

